package psd.model.Prolog.Converters;

import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;

import psd.model.IConverter;
import psd.model.Prolog.FactGenerationToolbox;
import psd.model.Prolog.PrologConverter;


public class PrologQualifiedNameConverter  extends PrologConverter implements
IConverter<QualifiedName>{

	public PrologQualifiedNameConverter(FactGenerationToolbox toolbox) {
		super(toolbox);
	}

	@Override
	public boolean convert(QualifiedName node) {
	    String name = node.getName().getIdentifier();
        if(node.getParent().getNodeType() == 55 || node.getParent().getNodeType() == 47 || node.getParent().getNodeType() == 48 || node.getParent().getNodeType() == 57 || node.getParent().getNodeType() == 52 || node.getParent().getNodeType() == 31)
        {
            return false;
        }
        if(node.resolveBinding().getKind() == 2)
        {
            handleSelectsIdents(node, null);
            return false;
        }
        if(node.resolveBinding().getKind() == 1)
        {
            generatePackageFactIfNecessary(node.resolveBinding());
        }
        generateGetFieldIfNodeIsFieldAccess(node, name);
        return false;
	}
	
	 private boolean generateGetFieldIfNodeIsFieldAccess(Name node, String name)
	    {
	        if(node.resolveBinding() == null)
	        {
	            return false;
	        }
	        if(node.resolveBinding().getKind() == 3 && ((IVariableBinding)node.resolveBinding()).isField())
	        {
	            String args[] = {
	                node.isSimpleName() ? quote("null") : idResolver.getID(((QualifiedName)node).getQualifier()), quote(name), idResolver.getID(node.resolveBinding())
	            };
	            createBodyFact(node, "getFieldT", args);
	            writeSourceLocationArgumentIdentifier(node, node);
	            if(!node.isSimpleName())
	            {
	                Name q = ((QualifiedName)node).getQualifier();
	                String atomName;
	                if(q.isSimpleName())
	                {
	                    atomName = ((SimpleName)q).getIdentifier();
	                } else
	                {
	                    atomName = ((QualifiedName)q).getName().getIdentifier();
	                }
	                if(!generateGetFieldIfNodeIsFieldAccess(q, atomName))
	                {
	                    handleSelectsIdents(q, null);
	                }
	            }
	            return true;
	        } else
	        {
	            return false;
	        }
	    }

}
